import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 private static final String UPLOAD_DIRECTORY="TempFolder";
 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String applicationPath=request.getServletContext().getRealPath("");
     String uploadPath=applicationPath+ File.separator+UPLOAD_DIRECTORY;
     String fileName=request.getParameter("fileName");
     if(fileName==null||fileName.isEmpty()){
         response.sendRedirect("download.jsp");
         return;
     }
     File file=new File(applicationPath+File.separator+fileName);
     if(!file.exists()){
         response.getWriter().println("文件不存在。");
         return;
     }
     String encodedFileName= URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
     response.setContentType("application/octet-stream");
     response.setHeader("Content-Disposition", "attachment; filename=\""+encodedFileName+"\"");
     response.setContentLengthLong((int)file.length());
    try(FileInputStream inStream=new FileInputStream(file);
        OutputStream outStream=response.getOutputStream()){
        byte[] buffer=new byte[4096];
        int bytesRead;
        while((bytesRead=inStream.read(buffer))!=-1){
            outStream.write(buffer,0,bytesRead);
        }
    }
 }
}
